/**
 * Created by HaiHui on 2017/10/17.
 */
/**
 * init combobox
 * @return {}
 */
//form转换成json格式
/**
 * 使用场景：提交form表单时，还需要额外的数据时。
 * 使用实例：
 * 		var formData = $("formId").serializeJson();
 * 		var extData = {productId: "123123"};
 * 		$.extend(formData, extData);
 *
 */
$.fn.extend({
    serializeJson:function(){
        var serializeObj={};
        var array=this.serializeArray();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });
        return serializeObj;
    }
});

function initCombo(combo, url, valueField, displayField, setValue) {
    $("#" + combo).empty();
    $.ajax({
        url: url,
        data: {},
        async: false,
        success: function(data) {
            var data = data.data;
            initSelect(combo, data, valueField, displayField, true, null, setValue);
        }
    });

}


function dictionaryCombo(combo, selectValue, setValue) {
    $("#" + combo).empty();
    $.ajax({
        url: "dic/getDic",
        data: {
        	dicType : selectValue
        },
        async: false,
        success: function(data) {
            var data = data.data;
            initSelect(combo, data, "dicId", "dicName", true, null, setValue);
        }
    });

}

function initSelect(selectId, data, dataId, dataText, emptyFlag, emptyValue, setValue) {
    var select = $("#" + selectId);
    select.empty();
    var option = null;
    if(emptyFlag != null && emptyFlag == true) {
        option = $("<option value=''>&nbsp;</option>")
        if(emptyValue != null) {
            option.val(emptyValue);
        }
        select.append(option);
    }
    if(data != null && data.length > 0) {
        for(var i = 0; i < data.length; i++) {
            option = $("<option></option>");
            option.val(data[i][dataId]);
            option.text(data[i][dataText]);

            select.append(option);
        }
    }

    $('#'+selectId +' option[value="' + setValue + '"]').attr('selected', true);

}
/**
 * ajax提交方法，用于提交表单，获取数据等。<br>
 * 使用实例：
 * 	 	var setting = {
 * 			url:basePath+"product/detail",
 * 			data:{id:productId}
 * 		}
 * 		ajaxSubmit(setting, loadProductSuccess, "获取商品详情失败");
 *
 * 		//获取商品详情提交成功
 * 		function loadProductSuccess(responseData){
 * 			.....
 * 		}
 *
 * @param setting json格式的ajax参数，包括：url, type, data, dataType<br>
 * 		url: ajax提交地址<br>
 * 		type: 提交方式（包括 post/get等)<br>
 * 		data: from表单数据（json或字符串格式）
 * 		dataType: 期待服务返回数据类型（包括json/html/text等）
 * @param successFn 提交成功消息或回调函数（类型：function/string),如果不设置，提交成功后会弹出默认提示“操作成功”<br>
 *
 * @param errorFn 提交失败消息或回调函数（类型：function/string),如果不设置，提交成功后会弹出默认提示“操作失败”<br>
 */
function ajaxSubmit(setting, successFn, errorFn) {
//	var layerLoading = layer.load(1, {
//		shade : [ 0.1, '#000' ]
//	});

    var defaultSetting = {
        type : "post",
        dataType : "json",
        async : true,
        loadingFlag : true,
        traditional: false,

        processData: true
    };

    $.extend(defaultSetting, setting);
    var layerLoading = null;
    if(defaultSetting.loadingFlag==true){
        layerLoading = layer.load(0, {
            shade : [0.5,'#F9F9F9']
        });
    }

//	var data = defaultSetting.data;
//	var url = defaultSetting.url;
//	var type = defaultSetting.type;
//	var dataType = defaultSetting.dataType;
    $.ajax({
        url : defaultSetting.url,
        data : defaultSetting.data,
        type : defaultSetting.type,
        async : defaultSetting.async,
        traditional : defaultSetting.traditional,
        dataType : defaultSetting.dataType,
        contentType: defaultSetting.contentType,
        processData: defaultSetting.processData,
        success : function(responseData) {
            if(layerLoading!=null){
                layer.close(layerLoading);
            }
            if (successFn != null) {
                var msg = "数据提交成功";
                if(typeof(successFn)=="string"){
                    msg = successFn;
                    successFn = getFunctionFromString(successFn);
                }
                if(typeof(successFn)=="function"){
                    successFn(responseData);
                } else {
                    layer.alert(msg);
                }
            }
        },
        error : function(xhr, statusText, error) {
            if(statusText=='parsererror'){
                window.location.reload();
                return
            }
            if(layerLoading!=null){
                layer.close(layerLoading);
            }
            var msg = "数据提交失败";
            if (errorFn != null) {
                if(typeof(errorFn)=="string"){
                    msg = errorFn;
                    errorFn = getFunctionFromString(errorFn);
                }
                if(typeof (errorFn) == "function"){
                    errorFn(xhr, statusText, error);
                } else {
                    layer.alert(msg);
                }
            } else {
                layer.alert(msg);
            }
        }
    });
}
/**
 * 检查提交成功结果，用于检查操作是否成功<br>
 * 使用方法：
 * 	 checkSubmitResult(responseData, {error:"流程添加失败", success:"流程添加成功"}),
 *
 *
 * @param responseData 服务器返回的数据
 * @param msgObj 消息信息（json格式）<br>
 * 		  success:操作成功提示消息<br>
 * 		  error:操作失败提示消息<br>
 * @param callback 操作成功的回调函数（可选），如果不指定则需要指定操作成功的提示消息
 */
function checkSubmitResult(responseData, msgObj, callback,failback) {
    if (msgObj == null) {
        msgObj = {};
    }
    msgObj.successDefault = "操作成功";
    msgObj.errorDefault = "操作失败";
    if (responseData != null) {
        if (responseData.result == true) {
            if (callback != null && typeof (callback) == "function") {
                callback(responseData);
            } else if (msgObj.success != null && msgObj.success != "") {
                layer.alert(msgObj.success);
            } else {
                layer.alert(msgObj.successDefault);
            }
        } else {
            if (failback != null && typeof (failback) == "function") {
                failback(responseData);
            }
            else{
                if(responseData.description!=null){
                    layer.alert(responseData.description);
                } else {
                    if(msgObj.error!=null && msgObj.error!=""){
                        layer.alert(msgObj.error);
                    } else {
                        layer.alert(msgObj.errorDefault);
                    }
                }
            }
        }
    } else {
        if(msgObj.error!=null && msgObj.error!=""){
            layer.alert(msgObj.error);
        } else {
            layer.alert(msgObj.errorDefault);
        }
    }
}